<?php

namespace App\Listeners\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\OpenShopCacheEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Events\OpenShop\OrderPaymentSucceededEvent;
use App\Events\OpenShop\ShopCreatedEvent;
use App\Events\OpenShop\ShopCreatedOnceEvent;
use App\Listeners\BaseListener;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Service\Common\SmsService;
use App\Service\OpenShop\Feishu\UserExtContractService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\Wap\SignOrderService;
use Illuminate\Support\Facades\Log;

class CreateShopListener extends BaseListener
{
    /**
     * 创建门店档案
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @param \App\Events\OpenShop\OrderPaymentSucceededEvent $event
     * @return void
     */
    public function handle(OrderPaymentSucceededEvent $event)
    {
        Log::channel('listener')->info(__CLASS__ . " handle...orderNo:" . $event->signOrder->orderNo);

        // 根据开店数量执行对应的事件
        $shopCount = $event->signOrder->contractRel->shopCount;

        for ($i = 0; $i < $shopCount; $i++) {

            // 根据开店数量生成子订单
            if ($i >= 1) {
                $currentOrderNo = (new SignOrderService($event->signOrder->orderNo))->createChildOrders();
            } else {
                $currentOrderNo = $event->signOrder->orderNo;
            }

            // 生成店铺
            $shop = (new SignOrderService($currentOrderNo))->shopBuild();
            dump($shop);
            Log::channel('listener')
               ->info(__CLASS__ . " handle create shop...orderNo: {$currentOrderNo} i:{$i}", $shop);

            $shopCode = $shop['shopCode'] ?? 0;
            $shopId   = $shop['shopId'] ?? 0;

            Log::channel('listener')
               ->info(__CLASS__ . " handle create shop...orderNo: {$currentOrderNo} i:{$i}", $shop);

            // 更新订单权限
            OrderService::updateOrderPermissionAnchor($currentOrderNo);

            // 店铺创建成功事件
            event(new ShopCreatedEvent($currentOrderNo, (string)$shopCode));

            // 流程日志事件
            $mainProcess = OpenShopMainProcessModel::query()->where('orderNo', $currentOrderNo)->orderBy('id', 'desc')->first();
            event(new OpenShopProcessEvent(
                0,
                $mainProcess->id,
                MainProcessEnum::MAIN_PROCESS_INVESTMENT_SIGN,
                MainProcessEnum::INVESTMENT_SIGN_CONTRACT_PAID
            ));

            if ($i == 0) {

                // 店铺创建成功-只需要执行一次的事件
                event(new ShopCreatedOnceEvent($currentOrderNo, (string)$shopCode, $event->payHistory, $event->payTime));
            }
        }
    }
}
